# -*- coding: utf-8 -*-
import numpy as np
from pathlib import Path
from datetime import datetime
import pyedflib
import debugPrinter as dp

class FileNameGenerator(object):
    def __init__(self, path_str_root):
        super(FileNameGenerator, self).__init__()
        self.fileNameCounter = 0
        self.path_str_root = path_str_root

    def generate_name(self):
        now = datetime.now()
        str_dateTime = now.strftime("%m%d%H%M")# %S
        path_str = self.path_str_root+"/"+str_dateTime
        if Path(path_str).exists():
            num = 1
            path_str_origin = path_str
            path_str = path_str_origin +"("+str(num)+")"
            while Path(path_str).exists():
                num = num+1
                path_str = path_str_origin+"("+str(num)+")"

        return path_str

    def get_file_name(self,path_str):
        txtName=self.fileName_first_letter+str(self.fileNameCounter)+self.extended_str
        self.fileNameCounter = self.fileNameCounter+1
        filePathName = path_str+"/"+txtName
        return filePathName

class EDFSaver(object):
    """docstring for FileSaver"""
    def __init__(self, path_str):
        super(EDFSaver, self).__init__()
        self.fng = FileNameGenerator(path_str)
        self.path_str = None
        self.data = None
        self.channel_info = []

        self.save_on = 0
        self.f=None
        # self.fs_eeg = 250
        self.fs_eeg = 500

        self.CH_NUM = 32

        self.filePathName = ''

    def make_path(self,path_str):
        if Path(path_str).exists():
            return 1

        Path(path_str).mkdir()
        self.path_str = path_str

        return 0

    def get_name(self):
        return self.fng.generate_name()

    def new_data(self,s,ts,d):
        if (self.save_on):
            # dp.dpt(ts.shape)
            # dp.dpt(d.shape)
            t = np.expand_dims(ts, axis=1)
            dd = np.hstack((t,d))
            if(s=='eeg'):
                self.data = np.concatenate((self.data,dd), axis=0)
                # dp.dpt(self.data[-1,:])
            if(s=='mar'):
                # self.data_marker = np.concatenate((self.data_marker,dd.astype(np.int32)), axis=0)
                self.data_marker = np.concatenate((self.data_marker,dd), axis=0)

    def setup(self,file_path_str,file_name_str):
        # ch_dict = {'label': 'lslts', 'dimension': 'ms', 'sample_frequency': 128}
        # self.channel_info.append(ch_dict)

        # ch_dict = {'label': 'F4', 'dimension': 'uV', 'sample_frequency': 128,'physical_max': 6553.6, 'physical_min': -6553.6, 
        #     'digital_max': 32767, 'digital_min': -32768, 'transducer': '', 'prefilter':''}
        # self.channel_info.append(ch_dict)
        # ch_list = [ 'TP9','C4','C3','F4',   'F3','Fp2','Fp1','Fz',
        #             'Oz','O2','O1','P4',    'P3','Pz','Cz','TP10',
        #             'FC6','FC2','FC1','FC5','F8','F7','AF4','AF3',
        #             'P8','P7','CP2','CP1',  'CP6','CP5','T8','T7']

        ch_list = [ 'TP9','C4','C3','F4',   'F3','Fp2','Fp1','Fz',
                    'TP10','Cz','Pz','P3',  'P4','O1','O2','Oz',
                    'AF3','AF4','F7','F8',  'FC5','FC1','FC2','FC6',
                    'P8','P7','CP2','CP1',  'CP6','CP5','T8','T7']

        for i in range(self.CH_NUM):
            ch_dict = {'label': ch_list[i], 'dimension': 'uV', 'sample_frequency': self.fs_eeg,'physical_max': 1125000, 'physical_min': -1125000, 
                'digital_max': 8388607, 'digital_min': -8388608, 'transducer': '', 'prefilter':''}
            self.channel_info.append(ch_dict)

        # ch_dict = {'label': ch_list[0], 'dimension': 'uV', 'sample_frequency': self.fs_eeg,'physical_max': 1125000, 'physical_min': -1125000, 
        #     'digital_max': 8388607, 'digital_min': -8388608, 'transducer': '', 'prefilter':''}
        # self.channel_info.append(ch_dict)


        self.data = np.empty(shape=(0,self.CH_NUM+1))

        # self.data_marker = np.empty(shape=(0,2),dtype=int)
        self.data_marker = np.empty(shape=(0,2))

        # self.filePathName = file_path_str+'/'+file_name_str+'_.edf'
        self.filePathName = file_path_str+'/'+file_name_str+'_.bdf'

        self.save_on = 1
        
    def flush_data(self):
        # self.f = pyedflib.EdfWriter(self.filePathName, 2,file_type=pyedflib.FILETYPE_EDFPLUS)
        # self.f = pyedflib.EdfWriter(self.filePathName, 24,file_type=pyedflib.FILETYPE_BDFPLUS)
        self.f = pyedflib.EdfWriter(self.filePathName, self.CH_NUM,file_type=pyedflib.FILETYPE_BDFPLUS)

        # print(len(self.channel_info))

        self.f.setSignalHeaders(self.channel_info)

############################ marker data
        data_save=None
        data_save = self.data.copy()

        t_arr = data_save[:,0]

        m_arr = self.data_marker[:,0]


        # dp.dpt(self.data_marker.shape)
        # dp.dpt(self.data_marker)


        m_index = np.searchsorted(t_arr, m_arr)
        #  now the ts is float, so do this first, then the ts will convert to int32, the milli-second time information will disappear
        m_t = m_index/self.fs_eeg 


        makers = self.data_marker[:,1]
        makers = makers.astype(np.int32)
        # for m in m_t:
        #     self.f.writeAnnotation(m, -1, str(v))
        for i, m in enumerate(m_t):
            self.f.writeAnnotation(m, -1, str(makers[i]))
            # dp.dpt(m)
            # dp.dpt(makers[i])
            # dp.dpt('----')

        # np.save('data_save.npy', data_save)
        # np.save('data_marker.npy', self.data_marker)

        # dp.dpt(m_arr)


############################ eeg data
        # self.data = self.data.astype(np.int32)

        data_save = data_save.astype(np.int32)

        # print('----------------')
        # print(data_save.shape)

        data_list=[]
        for i in range(data_save.shape[1]-1):
            tmp = data_save[:,i+1].copy()
            data_list.append(tmp)

        # data_list=[]
        # for i in range(data_save.shape[1]-1):
            # tmp = data_save[:,i+1].astype(np.float32)*0.067
            # gain=8,ref=4.5v*2,24bit,LSB=0.067uV
            # data_list.append(tmp)

############################ marker data



############################ save
        # print(len(data_list))

        self.f.writeSamples(data_list,digital=True)
        # self.f.writeSamples(data_list)
        self.f.close()

        self.save_on = 0

        dp.dpt(self.filePathName + ' , saved')
        # del self.f




